package driver.android;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import driver.android.adapter.TaskListAdapter;
import driver.android.http.CommonOkHttpClient;
import driver.android.view.RotationLoadingView;
import driver.util.Constants;
import driver.util.IHttpCallBack;
import driver.util.TaskInfo;
import driver.util.Util;
import okhttp3.Response;

/*
 * tasks list Activity
 */
public class FlashDriverPackageListActivity extends FragmentActivity implements IHttpCallBack, View.OnClickListener, LocationListener, CompoundButton.OnCheckedChangeListener, PopupMenu.OnMenuItemClickListener, AdapterView.OnItemClickListener {

    private String mLoginToken;
    private String mUuid;
    private ProgressDialog mProgressDialog;
    private FlashDriverTaskHandler mHandler;
    private String mRequestTaskType = "userInfo";
    private RelativeLayout mTaskDetailRelativeLayout;
    private SharedPreferences mFlashSharedPreferences;
    private String mFlashSharePreferenceName = "Flash";
    private String mLatitude; //Latitude
    private String mLongitude; //Longitude
    private LocationManager mLocationManager;
    private TextView mUserName;
    private Button mEarningButton;
    private Button mUserDetailIcon;
    private Switch mOnOffLineSwitch;
    private String mFromActivityName = "";
    private String mUserInfo = "";
    private PopupMenu popupMenu;
    private ListView mInProgressTaskListView;
    private TaskListAdapter mTaskListAdapter;
    private List<TaskInfo> mInProgressTaskList;
    private String mIgnoreTaskId = "";
    private RotationLoadingView mRotationLoadingView;
    private Button mPendingLoading;
    private String mMaxUploadPics = "2";
    private String mUpdateLocation = "false";
    private LinkedHashMap mMenusMap = new LinkedHashMap<String, String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Util.debugApp('d', "task list activity on create");
        setContentView(R.layout.f_activity_task);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            mOnOffLineSwitch.setClickable(false);
            return;
        }
        mPendingLoading.setVisibility(View.VISIBLE);
        mRotationLoadingView.setStartAnimation(false);
        mRotationLoadingView.setVisibility(View.INVISIBLE);
        registerLocationListen();
        unShowPopMenu();
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            mFromActivityName = bundle.get("reShowPackage").toString();
            mIgnoreTaskId = bundle.get("taskId").toString();
        }
        Util.debugApp('d', "task list activity on resume from " + mFromActivityName);
        this.showProgressDialog("Please wait...");
        getUserInfo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Util.debugApp('d', "task list activity on pause");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Util.debugApp('d', "task list activity on Destroy");
        mLocationManager.removeUpdates(this);
        mHandler.removeCallbacksAndMessages(null);
    }

    private void initView() {
        mProgressDialog = new ProgressDialog(this);
        mHandler = new FlashDriverTaskHandler(this);
        mTaskDetailRelativeLayout = (RelativeLayout) this.findViewById(R.id.new_task_layout);
        mFlashSharedPreferences = getSharedPreferences(mFlashSharePreferenceName, Context.MODE_PRIVATE);
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mUserName = (TextView) this.findViewById(R.id.user_name_text_view);
        mEarningButton = (Button) this.findViewById(R.id.task_fee);
        if (Util.DEBUG) {
            mEarningButton.setOnClickListener(this);
        }
        mUserDetailIcon = (Button) this.findViewById(R.id.user_detail_icon);
        mUserDetailIcon.setOnClickListener(this);
        mOnOffLineSwitch = (Switch) this.findViewById(R.id.user_on_line_switch);
        mOnOffLineSwitch.setOnCheckedChangeListener(this);
        mLoginToken = mFlashSharedPreferences.getString("token", "");
        mUuid = mFlashSharedPreferences.getString("uuid", "");
        mInProgressTaskListView = findViewById(R.id.in_progress_task_list);
        mInProgressTaskList = new ArrayList<TaskInfo>();
        mTaskListAdapter = new TaskListAdapter(this, R.layout.f_in_progress_task_item, mInProgressTaskList);
        mInProgressTaskListView.setAdapter(mTaskListAdapter);
        mInProgressTaskListView.setOnItemClickListener(this);
        popupMenu = new PopupMenu(this, mUserDetailIcon);
        popupMenu.setOnMenuItemClickListener(this);
        mRotationLoadingView = (RotationLoadingView) this.findViewById(R.id.loading);
        mPendingLoading = (Button) this.findViewById(R.id.search_available_task_btn_normal);
        mPendingLoading.setOnClickListener(this);
        mRotationLoadingView.setStartAnimation(false);
        mRotationLoadingView.setOnClickListener(this);
        Util.debugApp('d', "task list Activity get mLoginToken " + mLoginToken + " " + mUuid);
    }

    private void addPopUpMenu(String menus) {
        Util.debugApp('d', "menu size" + mMenusMap.size());
        mMenusMap.clear();
        mMenusMap.put("PROFILE", "");
        mMenusMap.put("EARNINGS", "");
        mMenusMap.put("PASSWORD", "");
        try {
            JSONArray jsonTaskArray = new JSONArray(menus);
            if (jsonTaskArray != null && jsonTaskArray.length() > 0) {
                for (int index = 0; index < jsonTaskArray.length(); index++) {
                    String menuJson = jsonTaskArray.get(index).toString();
                    String menu = Util.getJsonKeyValue("label", menuJson) == null ? "" : Util.getJsonKeyValue("label", menuJson);
                    String menuLink = Util.getJsonKeyValue("link", menuJson) == null ? "" : Util.getJsonKeyValue("link", menuJson);
                    mMenusMap.put(menu, menuLink);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mMenusMap.put("LOGOUT", "");
        popupMenu.getMenu().clear();
        Iterator iterator = mMenusMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            popupMenu.getMenu().add(Menu.NONE, Menu.FIRST, Menu.NONE, key);
        }
    }

    private void showToast(String title) {
        Toast.makeText(this, title, Toast.LENGTH_LONG).show();
    }

    private void getUserInfo() {
        if (mLoginToken != null && mUuid != null) {
            mRequestTaskType = "userInfo";
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            Map<String, String> headersParams = new HashMap<>();
            headersParams.put("token", mLoginToken);
            this.addLocationParams(headersParams);
            String url = Constants.ROOT + mUuid + Constants.USER_INFO;
            Util.debugApp('d', "get user info " + url);
            okHttpInstance.doGet(url, headersParams, null);
        }
    }

    private void showProgressDialog(String title) {
        if (mProgressDialog != null) {
            mProgressDialog.setMessage(title);
            mProgressDialog.setCanceledOnTouchOutside(false);
            if (!this.isFinishing()) {
                mProgressDialog.show();
            }
        }
    }

    private void closeProgressDialog() {
        if (!this.isFinishing() && mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void getProcessTask(String type) {
        if (mLoginToken != null && mUuid != null) {
            mRequestTaskType = type;
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            Map<String, String> headersParams = new HashMap<>();
            headersParams.put("token", mLoginToken);
            this.addLocationParams(headersParams);
            String taskUrl = "";
            if (Util.DEBUG) {
                mLatitude = "46.4542097";
                mLongitude = "-81.0215526";
            }
            if (type.equals("process")) {
                taskUrl = Constants.ROOT + mUuid + Constants.TASK_IN_PROGRESS;
            } else {
                taskUrl = Constants.ROOT + mUuid + Constants.TASK_IN_AVAILABLE + "?lat=" + mLatitude + "&lng=" + mLongitude;
            }
            Util.debugApp('d', "get task url " + taskUrl + " " + mRequestTaskType);
            okHttpInstance.doGet(taskUrl, headersParams, null);
        }
    }

    private void ignoreTask() {
        mLoginToken = mFlashSharedPreferences.getString("token", "");
        mUuid = mFlashSharedPreferences.getString("uuid", "");
        if (mLoginToken != null && mUuid != null) {
            mRequestTaskType = "ignoreTask";
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            Map<String, String> headersParams = new HashMap<>();
            headersParams.put("token", mLoginToken);
            this.addLocationParams(headersParams);
            String taskUrl = Constants.ROOT + mUuid + Constants.TASK_IGNORE;
            Util.debugApp('d', "get ignore url " + taskUrl + " " + mRequestTaskType);
            Map<String, String> params = new HashMap<>();
            params.put("taskid", mIgnoreTaskId);
            okHttpInstance.doPut(taskUrl, headersParams, params);
        }
    }

    private void parseJsonBundle(Bundle bundle) {
        String taskJsonDetail = bundle.getString("taskBody");
        Util.debugApp('d', "parse json mRequestTaskType is " + mRequestTaskType + " " + taskJsonDetail);
        if (mRequestTaskType.equals("onLineState")) {
            String state = Util.getJsonKeyValue("accept_delivery_task", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("accept_delivery_task", taskJsonDetail);
            Util.debugApp('d', "change user state " + state);
            if (state.equals("1")) {
                mOnOffLineSwitch.setChecked(true);
                mPendingLoading.setVisibility(View.VISIBLE);
            } else if (state.equals("0")) {
                mOnOffLineSwitch.setChecked(false);
                mHandler.removeCallbacksAndMessages(null);
                mPendingLoading.setVisibility(View.INVISIBLE);
                mRotationLoadingView.setVisibility(View.INVISIBLE);
            }
        } else if (mRequestTaskType.equals("ignoreTask")) {
            mRotationLoadingView.setStartAnimation(true);
            mRotationLoadingView.postInvalidate();
            getProcessTask("available");
        } else if (mRequestTaskType.equals("logout")) {
            if (taskJsonDetail != null && taskJsonDetail.equals("true")) {
                SharedPreferences.Editor editor = mFlashSharedPreferences.edit();
                editor.putString("token", "");
                editor.putString("uuid", "");
                editor.commit();
                Intent intent = new Intent();
                intent.setClass(this, FlashDriverLoginActivity.class);
                this.startActivity(intent);
                this.finish();
            } else if (taskJsonDetail != null && taskJsonDetail.equals("false")) {
                showToast("Network Error...");
            }
        } else if (mRequestTaskType.equals("userInfo")) {
            mUserInfo = taskJsonDetail;
            String firstName = Util.getJsonKeyValue("d_first_name", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("d_first_name", taskJsonDetail);
            String lastName = Util.getJsonKeyValue("d_last_name", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("d_last_name", taskJsonDetail);
            String menuJsonArray = Util.getJsonKeyValue("appmenu", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("appmenu", taskJsonDetail);
            addPopUpMenu(menuJsonArray);
            mUserName.setText(firstName + " " + lastName);
            String earning = Util.getJsonKeyValue("earnings", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("earnings", taskJsonDetail);
            String earningTotal = earning.equals("null") ? "" : earning;
            String appSettingJson = Util.getJsonKeyValue("setting", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("setting", taskJsonDetail);
            mMaxUploadPics = Util.getJsonKeyValue("MAXIMUM_UPLOADED_IMAGES", appSettingJson) == null ? "" : Util.getJsonKeyValue("MAXIMUM_UPLOADED_IMAGES", appSettingJson);
            Util.debugApp('d', "max upload pics size " +  mMaxUploadPics);
            mUpdateLocation = Util.getJsonKeyValue("UPDATE_LOCATION_INFORMATION", appSettingJson) == null ? "" : Util.getJsonKeyValue("UPDATE_LOCATION_INFORMATION", appSettingJson);
            mUpdateLocation = mUpdateLocation.toLowerCase();
            Util.debugApp('d', "update location flag " +  mUpdateLocation);
            if (earningTotal.length() > 0) {
                mEarningButton.setText("$ " + earningTotal);
            } else {
                mEarningButton.setText("$ " + 0);
            }
            String activeTask = Util.getJsonKeyValue("active_task", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("active_task", taskJsonDetail);
            String offLine = Util.getJsonKeyValue("accept_delivery_task", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("accept_delivery_task", taskJsonDetail);
            Util.debugApp('d', "user is on line " + offLine + " process task " + activeTask + " mFromActivityName " + mFromActivityName + " mIgnoreTaskId " + mIgnoreTaskId);
            if (offLine.equals("0")) {
                mOnOffLineSwitch.setChecked(false);
                mPendingLoading.setVisibility(View.INVISIBLE);
            } else {
                mPendingLoading.setVisibility(View.VISIBLE);
                mOnOffLineSwitch.setChecked(true);
            }
            if (!activeTask.equals("0") && !activeTask.equals("null")) {
                Util.debugApp('d', "had process task");
                mTaskDetailRelativeLayout.setVisibility(View.VISIBLE);
//                this.showProgressDialog("Please wait...");
                getProcessTask("process");
            } else {
                Util.debugApp('d', "had not process task");
                mTaskDetailRelativeLayout.setVisibility(View.GONE);
            }
//            ignore the task when countdown over
            if (mFromActivityName.equals("true") && !mIgnoreTaskId.isEmpty()) {
                Util.debugApp('d', "countdown over " + mIgnoreTaskId);
                ignoreTask();
            }
        } else {
            Util.debugApp('d', "start parse json " + taskJsonDetail);
            try {
                JSONArray jsonTaskArray = new JSONArray(taskJsonDetail);
                Util.debugApp('d', "start parse jsonTakArray length " + jsonTaskArray.length() + " mRequestTaskType " + mRequestTaskType);
                if (mRequestTaskType.equals("available")) {
                    if (jsonTaskArray.length() == 0) {
                        Message getAvailTaskMessage = mHandler.obtainMessage();
                        getAvailTaskMessage.what = Constants.AVAILABLE_TASK_AT_TIME;
                        mHandler.sendMessageDelayed(getAvailTaskMessage, 10 * 1000);
                    } else {
                        playDing();
                        mHandler.removeCallbacksAndMessages(null);
                        String json = jsonTaskArray.get(0).toString();
                        String taskId = Util.getJsonKeyValue("taskid", json) == null ? "" : Util.getJsonKeyValue("taskid", json);
                        showTaskDetailActivity(taskId);
                    }
                } else {
                    mInProgressTaskList.clear();
                    if (jsonTaskArray.length() == 0) {
                    } else {
                        updateUi(jsonTaskArray);
                    }
                }
            } catch (JSONException e) {
            }
        }
    }

    private void playDing() {
        Uri mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone mRingtone = RingtoneManager.getRingtone(this, mUri);
        mRingtone.play();
    }

    private void updateUi(JSONArray array) {
        int length = array.length();
        for (int index = 0; index < length; index++) {
            try {
                String taskItemJson = array.get(index).toString();
                Util.debugApp('d', "the process task is " + taskItemJson);
                String state = Util.getJsonKeyValue("task_status", taskItemJson) == null ? "" : Util.getJsonKeyValue("task_status", taskItemJson);
                String date = Util.getJsonKeyValue("collect_datetime", taskItemJson) == null ? "" : Util.getJsonKeyValue("collect_datetime", taskItemJson);
                String address = Util.getJsonKeyValue("r_address1", taskItemJson) == null ? "" : Util.getJsonKeyValue("r_address1", taskItemJson);
                String taskId = Util.getJsonKeyValue("taskid", taskItemJson) == null ? "" : Util.getJsonKeyValue("taskid", taskItemJson);
                Util.debugApp('d', "task info " + taskId + " " + state + " " + date + " " + address);
                TaskInfo task = new TaskInfo();
                task.setTaskId(taskId);
                task.setTaskSummary("[" + state + "]");
                task.setTaskDate(date);
                task.setTaskAddress(address);
                mInProgressTaskList.add(task);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (mInProgressTaskList.size() > 0) {
            mTaskListAdapter.notifyDataSetChanged();
        }
    }

    private void showTaskDetailActivity(String id) {
        Util.debugApp('d', "task id  " + id);
        Intent intent = new Intent();
        intent.setClass(this, FlashDriverTaskDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("token", mLoginToken);
        bundle.putString("uuid", mUuid);
        String taskId = id;
        bundle.putString("taskId", taskId);
        bundle.putString("maxUploadPics", mMaxUploadPics);
        bundle.putString("mUpdateLocation", mUpdateLocation);
        intent.putExtras(bundle);
        this.startActivity(intent);
    }

    private void handlerNetWorkError() {
        Toast.makeText(this, "Sorry, NetWork Error...", Toast.LENGTH_SHORT).show();
    }

    private void registerLocationListen() {
        Criteria criteria = new Criteria();
        String provider = mLocationManager.getBestProvider(criteria, false);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Please Allow Location Permission", Toast.LENGTH_LONG).show();
            return;
        }
        try {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0, this);
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 0, this);
        } catch (Exception e) {
            Util.debugApp('d', "requestLocationUpdates exception" + e.toString());
        }
    }

    private void updateWithNewLocation(Location location) {
        mLatitude = String.valueOf(location.getLatitude());
        mLongitude = String.valueOf(location.getLongitude());
        Util.debugApp('d', "current position mLatitude " + mLatitude + " mLongitude " + mLongitude);
        if (Util.DEBUG) {
            showToast("current position mLatitude" + mLongitude + " mLongitude " + mLongitude);
        }
        mLocationManager.removeUpdates(this);
    }

    private void changeUserLineState(String check) {
        if (mLoginToken != null && mUuid != null) {
            mRequestTaskType = "onLineState";
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            Map<String, String> headersParams = new HashMap<>();
            headersParams.put("token", mLoginToken);
            this.addLocationParams(headersParams);
            Map<String, String> params = new HashMap<>();
            params.put("accept_delivery_task", check);
            String url = Constants.ROOT + mUuid + Constants.ON_LINE_INFO;
            Util.debugApp('d', "change user state " + url);
            okHttpInstance.doPut(url, headersParams, params);
        }
    }

    private void addLocationParams(Map<String, String> headersParams) {
        Util.debugApp('d', "add location params " + mUpdateLocation + " " + mLatitude + " " + mLongitude);
        if (mUpdateLocation.equals("true") && !TextUtils.isEmpty(this.mLatitude) && !TextUtils.isEmpty(this.mLongitude)) {
            headersParams.put("lat", this.mLatitude);
            headersParams.put("lng", this.mLongitude);
        }
    }

    private void showLoginActivity() {
        SharedPreferences.Editor editor = mFlashSharedPreferences.edit();
        editor.putString("token", "");
        editor.putString("uuid", "");
        editor.commit();
        Intent intent = new Intent();
        intent.setClass(this, FlashDriverLoginActivity.class);
        this.startActivity(intent);
        this.finish();
    }

    // show menu
    public void showPopMenu() {
        if (popupMenu != null) {
            popupMenu.show();
        }
    }

    //    close menu
    private void unShowPopMenu() {
        if (popupMenu != null) {
            popupMenu.dismiss();
        }
    }

    private void logout() {
        if (mLoginToken != null) {
            mRequestTaskType = "logout";
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            Map<String, String> headersParams = new HashMap<>();
            headersParams.put("token", mLoginToken);
            this.addLocationParams(headersParams);
            String url = Constants.ROOT + mUuid + Constants.LOG_OUT;
            Util.debugApp('d', "logout url " + url);
            okHttpInstance.doPut(url, headersParams, null);
        }
    }

    @Override
    public void success(Response response) {
        Message getTaskSuccessMessage = mHandler.obtainMessage();
        Bundle bundle = new Bundle();
        try {
            String body = response.body().string();
            getTaskSuccessMessage.what = Constants.PROGRESS_RECEIVE_SUCCESS_MESSAGE;
            bundle.putString("taskBody", body);
            getTaskSuccessMessage.setData(bundle);
            Util.debugApp('d', "server body " + body);
        } catch (IOException e) {
            Util.debugApp('e', "get server success bug parse error" + e.toString());
            getTaskSuccessMessage.what = Constants.LOGIN_SUCCESS_FORMAT_ERROR;
        }
        mHandler.sendMessage(getTaskSuccessMessage);
    }

    @Override
    public void fail(IOException exception) {
        if (mHandler != null) {
            Message getTaskFailMessage = mHandler.obtainMessage();
            if (getTaskFailMessage != null) {
                getTaskFailMessage.what = Constants.PROGRESS_RECEIVE_FAIL_MESSAGE;
                mHandler.sendMessage(getTaskFailMessage);
            }
            Util.debugApp('d', "get serve fail" + exception.toString());
        }
    }

    @Override
    public void codeInvalid(Response response) {
        if (mHandler != null) {
            Message unKnowMessage = mHandler.obtainMessage();
            if (unKnowMessage != null) {
                int code = response.code();
                if (code == 401) {
                    unKnowMessage.what = Constants.UN_KNOW_RESPONSE_401_CODE;
                } else {
                    try {
                        String body = response.body().string();
                        Util.debugApp('d', "codeInvalid " + body);
                        Bundle bundle = new Bundle();
                        bundle.putString("codeInvalid", body);
                        unKnowMessage.what = Constants.UN_KNOW_RESPONSE_CODE;
                        unKnowMessage.setData(bundle);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                mHandler.sendMessage(unKnowMessage);
            }
        }
    }

    @Override
    public void onClick(View v) {
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            return;
        }
        mHandler.removeCallbacksAndMessages(null);
        int id = v.getId();
        switch (id) {
            case R.id.task_fee:
                break;
            case R.id.user_detail_icon:
                Util.debugApp('d', "user_detail_icon");
                showPopMenu();
                break;
            case R.id.search_available_task_btn_normal:
                mRotationLoadingView.setStartAnimation(true);
                mRotationLoadingView.postInvalidate();
                mPendingLoading.setVisibility(View.INVISIBLE);
                mRotationLoadingView.setVisibility(View.VISIBLE);
                getProcessTask("available");
                break;
            case R.id.loading:
                mRotationLoadingView.setStartAnimation(false);
                mPendingLoading.setVisibility(View.VISIBLE);
                mRotationLoadingView.setVisibility(View.INVISIBLE);
                mHandler.removeCallbacksAndMessages(null);
                break;
        }
    }

    @Override
    public void onLocationChanged(@NonNull Location location) {
        updateWithNewLocation(location);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(@NonNull String provider) {

    }

    @Override
    public void onProviderDisabled(@NonNull String provider) {

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!buttonView.isPressed()) {
            return;
        }
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            return;
        }
        mHandler.removeCallbacksAndMessages(null);
        this.showProgressDialog("please wait");
        String check = isChecked ? "1" : "0";
        this.changeUserLineState(check);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        String title = item.getTitle().toString();
        if (title.equals("PROFILE")) {
            Util.debugApp('d', "menu_user_info");
            Intent intentUserInfo = new Intent();
            intentUserInfo.setClass(this, FlashDriverUserInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("userInfo", mUserInfo);
            bundle.putBoolean("showSetting", false);
            intentUserInfo.putExtras(bundle);
            this.startActivity(intentUserInfo);
        } else if (title.equals("EARNINGS")) {
            Util.debugApp('d', "menu_billing_summary");
            Intent intentEarnings = new Intent();
            intentEarnings.setClass(this, FlashDriverSummaryActivity.class);
            this.startActivity(intentEarnings);
        } else if (title.equals("PASSWORD")) {
            Util.debugApp('d', "menu_update_password");
            Intent intentUpdatePassword = new Intent();
            intentUpdatePassword.setClass(this, FlashDriverUpdatePasswordActivity.class);
            this.startActivity(intentUpdatePassword);
        } else if (title.equals("LOGOUT")) {
            showProgressDialog("Please wait...");
            logout();
        } else {
            String link = this.mMenusMap.get(title).toString();
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(link);
            intent.setData(content_url);
            startActivity(intent);
        }
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mHandler.removeCallbacksAndMessages(null);
        TextView taskIdTv = (TextView) view.findViewById(R.id.new_task_summary_state);
        String taskId = taskIdTv.getTag(R.id.taskid).toString();
        Util.debugApp('d', "listView item click " + position + " " + id + " task id " + taskId);
        showTaskDetailActivity(taskId);
    }

    private static class FlashDriverTaskHandler extends Handler {

        private final WeakReference<FlashDriverPackageListActivity> mActivity;

        private FlashDriverTaskHandler(FlashDriverPackageListActivity ac) {
            this.mActivity = new WeakReference<FlashDriverPackageListActivity>(ac);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FlashDriverPackageListActivity activity = mActivity.get();
            if (activity != null && !activity.isFinishing()) {
                activity.closeProgressDialog();
                switch (msg.what) {
                    case Constants.PROGRESS_RECEIVE_SUCCESS_MESSAGE:
                        Util.debugApp('d', "PROGRESS_RECEIVE_SUCCESS_MESSAGE");
                        Bundle bundle = msg.getData();
                        activity.parseJsonBundle(bundle);
                        break;
                    case Constants.PROGRESS_RECEIVE_FAIL_MESSAGE:
                        Util.debugApp('d', "PROGRESS_RECEIVE_FAIL_MESSAGE");
                        activity.handlerNetWorkError();
                        break;
                    case Constants.AVAILABLE_TASK_AT_TIME:
                        Util.debugApp('d', "AVAILABLE_TASK_AT_TIME");
                        activity.getProcessTask("available");
                        break;
                    case Constants.UN_KNOW_RESPONSE_401_CODE:
                        activity.showLoginActivity();
                        break;
                    case Constants.UN_KNOW_RESPONSE_CODE:
                        Bundle bundleUnKnowCode = msg.getData();
                        String unKnowBody = bundleUnKnowCode.getString("codeInvalid");
                        String description = Util.getJsonKeyValue("description", unKnowBody);
                        if (description == null) {
                            activity.showToast("Network Error");
                        } else {
                            activity.showToast(description);
                        }
                        removeCallbacksAndMessages(null);
                        break;
                }
            }
        }
    }
}
